package com.bawei.property.view

import android.annotation.SuppressLint
import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.image.GlideEngine
import com.bawei.property.R
import com.bawei.property.adapter.CarColorAdapter
import com.bawei.property.adapter.CarImageAdapter
import com.bawei.property.databinding.ActivityParkSelectBinding
import com.bawei.property.entity.CarColorValue
import com.bawei.property.entity.CarImageEntity
import com.bawei.property.entity.ParkValue
import com.bawei.property.intent.ParkViewIntent
import com.bawei.property.state.ParkUiState
import com.bawei.property.vm.ParkViewModel
import com.blankj.utilcode.util.GsonUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Date

@AndroidEntryPoint
@Route(path = RoutePath.PATH_PARK_SELECT_PAGE)
class ParkSelectActivity : BaseMviActivity<ActivityParkSelectBinding>() {

    private val mViewModel: ParkViewModel by viewModels()

    @Autowired
    lateinit var parkEntity: ParkValue

    lateinit var mCarColorAdapter: CarColorAdapter
    lateinit var mCarImageAdapter: CarImageAdapter

    private var mCarImgList = mutableListOf<CarImageEntity>()


    override fun getLayoutId(): Int = R.layout.activity_park_select

    @SuppressLint("SetTextI18n")
    override fun initViews() {
        ARouter.getInstance().inject(this)
        mDataBinding.includePageTitle.ivBack.setOnClickListener {
            this@ParkSelectActivity.finish()
        }
        mDataBinding.includePageTitle.tvTitle.text = "车位信息修改"
        var startDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(parkEntity.parkStart.toLong() * 1000L)).toString()
        var endDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(parkEntity.parkEnd.toLong() * 1000L)).toString()
        mDataBinding.tvUseDate.text = "$startDate - $endDate"
        mDataBinding.tvApplyName.text = parkEntity.parkName
        mDataBinding.tvApplyDate.text = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(parkEntity.parkTime.toLong() * 1000L)).toString()

        //车辆颜色
        mDataBinding.rvCarColors.layoutManager = LinearLayoutManager(this@ParkSelectActivity, LinearLayoutManager.HORIZONTAL, false)
        mCarColorAdapter = CarColorAdapter(R.layout.item_car_color)
        mDataBinding.rvCarColors.adapter = mCarColorAdapter

        //车辆图片
        mDataBinding.rvCarImgs.layoutManager = LinearLayoutManager(this@ParkSelectActivity, LinearLayoutManager.HORIZONTAL, false)
        mCarImageAdapter = CarImageAdapter(mCarImgList)
        mDataBinding.rvCarImgs.adapter = mCarImageAdapter

                //添加车辆图片点击事件
        mDataBinding.ivAddCarImg.setOnClickListener {
            PictureSelector.create(this@ParkSelectActivity)
                .openGallery(SelectMimeType.ofImage()) //图片相册
                .setImageEngine(GlideEngine.createGlideEngine()) //图片加载器
                .forResult(object : OnResultCallbackListener<LocalMedia>{
                    override fun onResult(result: ArrayList<LocalMedia>) {
                        result.forEach {
                            mCarImgList.add(CarImageEntity(it.availablePath, it.availablePath.substring(it.availablePath.lastIndexOf("/") + 1)))
                        }
                        //设置到数据适配器中
                        mCarImageAdapter.notifyDataSetChanged()

                        //上传图片
                        uploadCarImages(mCarImgList)
                    }

                    override fun onCancel() {

                    }
                })
        }

        //提交车辆信息
        mDataBinding.tvSubmit.setOnClickListener {
            lifecycleScope.launch {
                mViewModel.channel.send(ParkViewIntent.SubmitParkIndo({}))
            }
        }

    }

    private fun uploadCarImages(list: MutableList<CarImageEntity>){
        lifecycleScope.launch {
            mViewModel.channel.send(ParkViewIntent.UploadCarImages(list as List<CarImageEntity>))
        }
    }


    override suspend fun sendViewIntent() {
        mViewModel.channel.send(ParkViewIntent.LoadCarColorList)
    }


    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is ParkUiState.LoadColorListSuccess -> {
                    mCarColorAdapter.data.addAll(it.data as MutableList<CarColorValue>)
                    mCarColorAdapter.notifyDataSetChanged()
                }
                is ParkUiState.UploadImageSuccess -> {
                    showToastMsg("上传成功")
                    Log.i("==========", "上传成功返回的图片地址：${GsonUtils.toJson(it.data as List<String>)}")
                }
                is ParkUiState.UploadImageFail -> showToastMsg(it.msg)
                is ParkUiState.LoadColorListFail -> showToastMsg(it.msg)
                else -> {}
            }

        }

    }



}